package top.andnux.weather.controller;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;

import top.andnux.weather.model.MainModel;
import top.andnux.weather.service.WeatherService;
import top.andnux.weather.view.MainView;

public class MainController extends BaseController<MainModel, MainView> {

    /**
     * 天气更新广播
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MainModel data = (MainModel) intent.getSerializableExtra("data");
            if (isAttachView()) {
                view.hideLoading();
                view.showMainView(data);
            }
        }
    };

    @SuppressWarnings("all")
    public MainController(Context context) {
        super(context);
        //注册广播
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            context.registerReceiver(receiver, new IntentFilter(WeatherService.ACTION), Context.RECEIVER_NOT_EXPORTED);
        } else {
            context.registerReceiver(receiver, new IntentFilter(WeatherService.ACTION));
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        //卸载广播
        context.unregisterReceiver(receiver);
    }

    @SuppressWarnings("all")
    public void loadWeather(Context context, String city) {
        WeatherService.start(context, city);
        if (isAttachView()) {
            view.showLoading("加载中...");
        }
    }
}
